const { pool } = require('../config/db');
const { getCurrentGroupId } = require('../utils/groupUtils');

exports.resolveTargetUrl = async (generatedLink) => {
    const conn = await pool.getConnection();
    try {
        // 获取资源
        const [resources] = await conn.query(
            'SELECT id FROM resources WHERE generated_link = ?',
            [generatedLink]
        );
        if (resources.length === 0) return null;

        const resourceId = resources[0].id;

        // 获取 system_status
        const [[status]] = await conn.query('SELECT * FROM system_status WHERE id = 1');

        // 获取启用的分组
        const [enabledGroups] = await conn.query('SELECT id, sort_order FROM redirect_groups WHERE is_enabled = TRUE ORDER BY sort_order');
        if (enabledGroups.length === 0) return null;

        const currentGroupId = getCurrentGroupId(status.visit_count, status.threshold, enabledGroups);

        // 更新访问计数
        // await conn.query('UPDATE system_status SET visit_count = visit_count + 1 WHERE id = 1');

        // 获取目标链接
        const [[target]] = await conn.query(
            'SELECT target_url FROM redirect_targets WHERE resource_id = ? AND group_id = ?',
            [resourceId, currentGroupId]
        );

        return target?.target_url || null;
    } finally {
        conn.release();
    }
};